package com.z.redis.command.impl;

import com.z.redis.RedisCore;
import com.z.redis.command.Command;
import com.z.redis.command.CommandType;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.SimpleString;
import io.netty.channel.ChannelHandlerContext;

/**
 * 选择数据库
 */
public class Select implements Command {
    private Integer index;
    @Override
    public CommandType type(){
        return CommandType.select;
    }

    @Override
    public void setContent(Resp[] array){
        try {
            if (array.length < 2 || !(array[1] instanceof BulkString)) {
                throw new IllegalArgumentException("Invalid SELECT command format");
            }
            this.index = Integer.parseInt(((BulkString) array[1]).getContent().toUTF8String());
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid database index: non-integer value");
        }
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        // TODO 切换数据库
        if(index>0){
            ctx.writeAndFlush(new SimpleString("-ERR invalid DB index"));
        }else {
            ctx.writeAndFlush(SimpleString.OK);
        }
    }
}
